package pucp.carpooling;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import pucp.carpooling.controller.JSONParserObject;

import com.google.android.gms.maps.SupportMapFragment;

import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragment;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class FragmentMapasAvisos extends SherlockFragment {
	private GoogleMap googleMap;
	float latend, lngend;
	private static final String url = "http://subete.inf.pucp.edu.pe/ServiciosMobile/obtener_avisos_todos";
	private final LatLng SUBETEPUCP = new LatLng(-12.069284, -77.078518);
	String[] tripDateTime,destinyName,detail,role;
	LatLng PuntoDestino;
	JSONArray avisos = null;
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		View rootView = null;
		

		try {
			// Loading map
			rootView = inflater.inflate(R.layout.fragment_mapa_avisos,
					container, false);
			initilizeMap();
			googleMap.addMarker(new MarkerOptions()
			.position(SUBETEPUCP)
			.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_action_student_map))
			.title(
					"Paradero PUCP"));

			LatLng coordinate = SUBETEPUCP;
			CameraUpdate myLocation = CameraUpdateFactory.newLatLngZoom(
					coordinate, 12);
			googleMap.animateCamera(myLocation);
			googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
			googleMap.setMyLocationEnabled(true);
			googleMap.getUiSettings().setZoomControlsEnabled(true);
			googleMap.getUiSettings().setMyLocationButtonEnabled(true);
			googleMap.getUiSettings().setCompassEnabled(true);
			googleMap.getUiSettings().setRotateGesturesEnabled(true);
			googleMap.getUiSettings().setZoomGesturesEnabled(true);
			
			new cargaMarkers().execute();

		} catch (Exception e) {
			e.printStackTrace();
		}
		return rootView;

	}

	private void initilizeMap() {

		if (googleMap == null) {
			googleMap = ((SupportMapFragment) getFragmentManager()
					.findFragmentById(R.id.mapReal)).getMap();

			if (googleMap == null) {
				Toast.makeText(getSherlockActivity(),
						"Sorry! unable to create maps", Toast.LENGTH_SHORT)
						.show();
			}

		}
	}

	@Override
	public void onResume() {
		super.onResume();
		initilizeMap();
	}

	@Override
	public void onPause() {
		super.onResume();
		initilizeMap();
	}
	
	private class cargaMarkers extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPreExecute() {

		}

		@Override
		protected Void doInBackground(Void... arg0) {
			try {

				JSONParserObject sh = new JSONParserObject();

			
				String jsonStr = sh.makeServiceCall(url, JSONParserObject.GET);
				Log.d("Response: ", "> " + jsonStr);
				if (jsonStr != null) {
					try {
						JSONObject jsonObj = new JSONObject(jsonStr);
						if (jsonObj.getString("Success").equals("Yes")) {
							avisos = jsonObj.getJSONArray("AvisosTodos");
							
							tripDateTime = new String[avisos.length()];
							destinyName = new String[avisos.length()];
							detail =  new String[avisos.length()];
							role = new String[avisos.length()];
														
							for (int i = 0; i < avisos.length(); i++) {
								JSONObject c = avisos.getJSONObject(i);
								tripDateTime[i] = " " +c.getString("TripDateTime");
								destinyName[i] = c.getString("DestinyName");		
								detail[i] = c.getString("Detail");
								role[i] = c.getString("Role");
								
							}
						} else {
							// no hay viajes pe :O
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}

			} catch (Exception e) {

			}

			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
		

			if (avisos != null) {
				for (int i = 0; i < avisos.length(); i++) {
					String coordenadas = detail[i];
					try {
						JSONObject jsonPuntos = new JSONObject(coordenadas);
						JSONObject end = jsonPuntos.getJSONObject("end");
						latend = Float.parseFloat(end.getString("lat"));
						lngend = Float.parseFloat(end.getString("lng"));
						
						PuntoDestino = new LatLng(latend,lngend);
						if (role[i].equals("Driver")) {
							googleMap.addMarker(new MarkerOptions()
							.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_action_driver_map))
							.position(PuntoDestino)
							.title(destinyName[i]));
						}
						else {
							googleMap.addMarker(new MarkerOptions()
							.icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_action_passenger_map))
							.position(PuntoDestino)
							.title(destinyName[i]));
						}
						
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
//					tripDateTime;
//					destinyName;
//					detail;
					
				}
			}
			

			
			super.onPostExecute(result);		
		}
		
		
	}


}
